<?php
#Funciones importantes
function Cookies($archivo,$datos=NULL){
	$archivo="sesion.txt";
	if(!$datos){
		if($fp = @fopen($archivo, "r")) $contenido = fread($fp, filesize($archivo));
		else return false;
	}else if($datos){
		if($fp = @fopen($archivo, "w+")){
			if (!fwrite($fp, $datos)) return false;      
		}else{
			return false;
		}
	}
    @fclose($fp); 
    if(isset($contenido)){
	return $contenido;
	}
}
function get_HTTP($host,$dir="/",$method="get",$is_ssl=false,$wcookie=false,$datos=false){
	$req  = strtoupper($method)." $dir HTTP/1.1\r\n";
	$req .= "Host: $host\r\n";
	$req .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3\r\n";
	$req .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
	$req .= "Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3\r\n";
	$req .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
	$req .= "Keep-Alive: 300\r\n";
	if(($cookies=unserialize(Cookies($host.".txt"))) && $wcookie){
		foreach($cookies as $k => $v){
			@$cookie .= "$k=$v[valor]; ";
		}
		$cookie=substr($cookie, 0, -2); 
		$req .= "Cookie: $cookie\r\n";
		$return['cookies']=$cookies;
	}
    $req .= "Connection: Close\r\n";
	if($datos){
		$req .= "Content-type: application/x-www-form-urlencoded\r\n";
		$req .= "Content-length: ".strlen($datos)."\r\n";
		$req .= "\r\n";
		$req .= $datos."\r\n";
	}else{
	$req .= "\r\n";
	}
	$return['solicitud'] = $req;
	if($is_ssl){$hostd="ssl://".$host;$port=443;}else{$port=80;}
	if($fp = fsockopen((($hostd)?$hostd:$host), $port, $errno, $errstr, 30)){
	fwrite($fp, $req);
	while (!feof($fp)) @$buffer .= fgets($fp, 128);
	fclose($fp);
	 }else{
		 die("Error");
	 }
	# Buffering in Vars
	$return['respuesta'] = $buffer;
	
	$buffer = explode("\r\n\r\n",$buffer,2);
	$return['encabezado'] = $buffer[0];
	$return['contenido'] = $buffer[1];
	
	$buffer=explode("\r\n",$buffer[0]);
	foreach($buffer as $v){
		$v=explode(": ",$v);
		# obtenemos Cookie
		if($v[0]=="Set-Cookie"){
			$v=explode(";",$v[1],2);
			$vb=$v[1];
			$v=explode("=",$v[0],2);
			$cookies[$v[0]]['valor']=$v[1];
			$cookies[$v[0]]['datos']=$vb;
		}
	}
	if($cookies) {
		$cookies=serialize($cookies);
		Cookies($host.".txt",$cookies);
	}
	return $return;
}
?>